package cn.net.isir.service2;

import com.alibaba.fastjson.JSONObject;
import cn.net.isir.dao.*;
import cn.net.isir.entity.NotifyTask;
import cn.net.isir.entity.Order;
import cn.net.isir.entity.OrderGoods;
import cn.net.isir.entity.Shop;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class PrintTaskService {
    @Resource
    private OrderDao orderDao;
    @Resource
    private GoodsDao goodsDao;
    @Resource
    private OrderGoodsDao orderGoodsDao;
    @Resource
    private ShopDao shopDao;
    @Resource
    private NotifyTaskDao notifyTaskDao;

    /**
     * 查询任务列表后,删除任务列表里的信息
     *
     * @param shopId 店铺id
     * @return 列表
     */
    public List<NotifyTask> queryTask(String shopId) {
        //查询打印任务列表
        NotifyTask notifyTask = new NotifyTask();
        notifyTask.setShopId(shopId);
        notifyTask.setPrintStatus("paid");//查询已支付状态的订单任务
        List<NotifyTask> notifyTaskList = notifyTaskDao.selectList(notifyTask);
        for (NotifyTask nt : notifyTaskList) {
            //设置订单商品
            Order order = orderDao.selectByOrderNo(nt.getOrderNo());
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderId(order.getId());
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(orderGoods);
            //设置打印区域
            for (OrderGoods og : orderGoodsList) {
                og.setScopeId(Integer.valueOf(goodsDao.selectByPrimaryKey(og.getGoodsId()).getPrintScope()));
                og.setName(og.getName() + "(" + og.getSpecName() + ")");
            }
            //设置牌号
            nt.setSerialNo(order.getSerialNumber());
            //设置店铺名称
            Shop shop = shopDao.selectByPrimaryKey(order.getShopId());
            nt.setShopName(shop.getName());
            nt.setAddress(shop.getAddress());
            nt.setTel(shop.getTel());
            nt.setOrderGoodsList(orderGoodsList);
            //传递其他信息(打包方式和口味备注)
            JSONObject otherInfo = new JSONObject();
            otherInfo.put("edibleMethod", order.getEdibleMethod());
            otherInfo.put("comment", order.getTaste());//备注(口味)
            nt.setOtherInfo(otherInfo.toJSONString());

            //更新
            NotifyTask ntUpdate = new NotifyTask();
            ntUpdate.setId(nt.getId());
            //更新通知状态
            ntUpdate.setPrintStatus("printed");//将已支付状态的任务,改为已打印
            ntUpdate.setPrintTime(new Date());
            notifyTaskDao.update(ntUpdate);
        }
        return notifyTaskList;
    }
}
